package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;

/**
 * 限定访问时间的拦截器:限定所有请求只能在每天的06:00-22:59 之间访问;
 */
@Slf4j
public class TimeAccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入限定访问时间的拦截器...");
        /*
            1.获取当前时间[小时];
            2.判断当前时间是否在限定的时间段内;
              2.1 在06:00-22:59之间: return true 放行;
              2.2 不在06:00-22:59之间: {"state":xxx, "message":"xxx", "data":"只能在06:00-22:59分之间进行访问"};
         */
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        if (hour < 6 || hour > 22){//不允许访问
            //{"state":3000, "message":"操作失败", "data":"只能在06:00-22:59分之间进行访问"};
            throw new RuntimeException("只能在06:00-22:59分之间进行访问");
        }
        //放行
        return true;
    }
}
